/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.security.action.Secure;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import org.apache.commons.lang.StringUtils;
import org.xptracker.domain.Domain;
import org.xptracker.domain.Queue;
import org.xptracker.domain.QueueType;
import org.xptracker.domain.User;
import org.xptracker.persistence.PersistenceManager;

import java.util.List;

@UrlBinding("/Queues.action")
@Secure(roles="planner")
public class QueuesActionBean extends StandardActionBean {
  private String queueId;
  private String queueName;
  private QueueType queueType;
  private List<Queue> queues;

  public List<Queue> getQueues() {
    return queues;
  }

  public void setQueues(List<Queue> queues) {
    this.queues = queues;
  }

  public QueueType getQueueType() {
    return queueType;
  }

  public void setQueueType(QueueType queueType) {
    this.queueType = queueType;
  }

  public String getQueueName() {
    return queueName;
  }

  public void setQueueName(String queueName) {
    this.queueName = queueName;
  }

  public String getQueueId() {
    return queueId;
  }

  public void setQueueId(String queueId) {
    this.queueId = queueId;
  }

  @DefaultHandler
  public Resolution listQueues() {
    return new ForwardResolution("/admin/queues.jsp");
  }

  @ValidationMethod(on = "Add")
  public void validateQueue(ValidationErrors errors) throws Exception {
    if (StringUtils.isBlank(queueName)) {
      errors.add("queueName", new SimpleError("Blank names are not allowed."));
    } else {
      Queue queue = domain.loadQueueByName(queueName);
      if (queue != null) {
        errors.add("queueName", new SimpleError("Queue ''{1}'' already exists.", queueName));
      }
    }
  }

  @HandlesEvent("Delete")
  public Resolution deleteQueue() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        Queue queue = loadEntity(Queue.class, queueId);
        for(User u: domain.listUsers()) {
          if (u.getQueues().remove(queue)) {
            receiver.update(u);
          }
        }
        receiver.remove(queue);
        getContext().getMessages().add(new SimpleMessage("Queue ''{0}'' removed.", queue.getName()));
        return new RedirectResolution(QueuesActionBean.class);
      }
    });
  }

  @HandlesEvent("Hide")
  public Resolution hideQueue() {
    return setHidden(true);
  }

  @HandlesEvent("Show")
  public Resolution showQueue() {
    return setHidden(false);
  }

  private Resolution setHidden(final boolean hidden) {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        Queue q = domain.loadEntity(Queue.class, queueId);
        q.setHidden(hidden);
        receiver.update(q);
        return new RedirectResolution(QueuesActionBean.class);
      }
    });
  }

  @HandlesEvent("Add")
  public Resolution addQueue() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        receiver.insert(new Queue(queueName));
        getContext().getMessages().add(new SimpleMessage("Queue ''{0}'' added.", queueName));
        return new RedirectResolution(QueuesActionBean.class);
      }
    });
  }

  @HandlesEvent("Open")
  public Resolution openQueue() {
    return setOpen(true);
  }

  @HandlesEvent("Close")
  public Resolution closeQueue() {
    return setOpen(false);
  }

  private Resolution setOpen(final boolean open) {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        Queue q = domain.loadEntity(Queue.class, queueId);
        q.setOpen(open);
        receiver.update(q);
        return new RedirectResolution(QueuesActionBean.class);
      }
    });
  }

  @HandlesEvent("ChangeType")
  public Resolution setQueueType() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        Queue q = domain.loadEntity(Queue.class, queueId);
        q.setType(queueType);
        receiver.update(q);
        return new RedirectResolution(QueuesActionBean.class);
      }
    });
  }

  @Before(stages=LifecycleStage.BindingAndValidation)
  public void provideQueues() {
    Domain domain = this.domain;
    this.queues = domain.listQueues(true);
  }
}
